/**
 * vim: tabstop=4
 * 
 * @license		http://www.gnu.org/licenses/gpl.html GPL Version 3
 * @author		Ian Moore <imooreyahoo@gmail.com>
 * @copyright	Copyright (c) 2011 Ian Moore
 * @version		$Id: dhcpd.js 12 2011-11-07 18:52:10Z imooreyahoo@gmail.com $
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this file. If not, see <http://www.gnu.org/licenses/>.
 */
//require("js/omv/NavigationPanel.js")
//require("js/omv/data/DataProxy.js")
//require("js/omv/FormPanelExt.js")
//require("js/omv/form/PasswordField.js")
//require("js/omv/form/SharedFolderComboBox.js")
//require("js/omv/form/plugins/FieldInfo.js")

Ext.ns("OMV.Module.Services");

//Register the menu.
OMV.NavigationPanelMgr.registerMenu("services", "dhcpd", {
	text: "DHCP",
	icon: "images/dhcpd.png"
});

OMV.Module.Services.DHCPDSettingsPanel = function(config) {
	var initialConfig = {
			rpcService: "DHCPD"
	};
	Ext.apply(initialConfig, config);
	OMV.Module.Services.DHCPDSettingsPanel.superclass.constructor.call(this, initialConfig);
};

Ext.extend(OMV.Module.Services.DHCPDSettingsPanel, OMV.FormPanelExt, {

	initComponent : function() {
		OMV.Module.Services.DHCPDSettingsPanel.superclass.initComponent.apply(this, arguments);
		this.on("load", this._updateFormFields, this);

		this.on("load",function(){

			// Disable other tabs?
			var checked = this.findFormField("enable").checked;
			var rp = this.ownerCt.find('title','Reservations');
			var lp = this.ownerCt.find('title','Leases');
			if(rp.length > 0) (checked ? rp[0].enable() : rp[0].disable());
			if(lp.length > 0) (checked ? lp[0].enable() : lp[0].disable());


		}, this);
	},

	getFormItems : function() {
		return [{
			xtype: "fieldset",
			title: "General settings",
			defaults: {
				labelSeparator: ""
			},
			items: [{
				xtype: "checkbox",
				name: "enable",
				fieldLabel: "Enable",
				checked: false,
				inputValue: 1,
				listeners: {
					check: this._updateFormFields,
					scope: this
				}
			},{
				xtype: "textfield",
				name: "domain-name",
				fieldLabel: "Domain Name",
				allowBlank: false,
				width : 300,
				value : "local"
			},{
				xtype: "textfield",
				name: "name-servers",
				fieldLabel: "Name Servers",
				allowBlank: true,
				width : 300,
				value : "",
				plugins: [ OMV.form.plugins.FieldInfo ],
				infoText: "Separate multiple entries with commas"
			},{
				xtype: "textfield",
				name: "wins-servers",
				fieldLabel: "WINS Servers",
				allowBlank: true,
				width : 300,
				value : "",
				plugins: [ OMV.form.plugins.FieldInfo ],
				infoText: "Separate multiple entries with commas"
			},{
				xtype: "textfield",
				name: "bootfile",
				fieldLabel: "TFTP Boot File",
				allowBlank: true,
				width : 300,
				value : "",
				plugins: [ OMV.form.plugins.FieldInfo ],
				infoText: "If set, this file must exist on the TFTP share."					
			},{
				xtype: "combo",
				name: "default-lease-time",
				fieldLabel: "Lease Time",
				allowBlank: false,
				displayField: "text",
				valueField: "value",
				value : "86400",
				triggerAction: "all",
				mode : "local",
				store : new Ext.data.SimpleStore({
					fields: [ "value","text" ],
					data: [
					       ["3600","1 hour"],
					       ["10800","3 hours"],
					       ["21600","6 hours"],
					       ["43200","12 hours"],
					       ["86400","1 day"],
					       ["172800","2 days"],
					       ["345600","4 days"],
					       ["604800","1 week"],
					       ]
				})
			}]
		},{
			xtype: "fieldset",
			title: "Lease Network",
			defaults: {
				labelSeparator: ""
			},
			items: [{
				xtype: "combo",
				name: "network",
				hiddenName: "network",
				fieldLabel: "Network",
				emptyText: "Select a network ...",
				allowBlank: false,
				allowNone: false,
				width: 300,
				editable: false,
				triggerAction: "all",
				displayField: "netid",
				valueField: "netid",
				store: new OMV.data.Store({
					remoteSort: false,
					proxy: new OMV.data.DataProxy("DHCPD", "getNetworks"),
					reader: new Ext.data.JsonReader({
						idProperty: "netid",
						fields: [
						         { name: "netid" }
						         ]
					})
				})
			},{
				xtype: "textfield",
				name: "gateway",
				fieldLabel: "Gateway",
				vtype: "IPv4",
				allowBlank: false,
				value : ""
			},{
				xtype: "textfield",
				name: "first-ip",
				fieldLabel: "First IP address",
				vtype: "IPv4",
				allowBlank: false,
				value : ""
			},{
				xtype: "textfield",
				name: "last-ip",
				vtype: "IPv4",
				fieldLabel: "Last IP address",
				allowBlank: false,
				value : ""
			}]
		}];
	},

	/**
	 * Private function to update the states of various form fields.
	 */
	_updateFormFields : function() {
		// Enabled / disabled fields
		var field = this.findFormField("enable");
		var checked = field.checked;
		var fields = [ "realm", "require-auth", "mntentref", "bootfile"];
		for (var i = 0; i < fields.length; i++) {
			field = this.findFormField(fields[i]);
			if (!Ext.isEmpty(field)) {
				if(field.name != "bootfile") field.allowBlank = !checked;
				field.setReadOnly(!checked);
			}
		}
	}
});

OMV.Module.Services.DHCPDReservationsGridPanel = function(config) {

	var initialConfig = {
			disabled: true,
			hidePagingToolbar: false,
			colModel: new Ext.grid.ColumnModel({
				columns: [{
					header: "Computer Name",
					sortable: true,
					dataIndex: "name",
					id: "name"
				},{
					header: "IP Address",
					sortable: true,
					dataIndex: "ip",
					id: "ip"
				},{
					header: "MAC Address",
					sortable: true,
					dataIndex: "mac",
					id: "mac"
                },{
                    header: "TFTP Boot File",
                    sortable: true,
                    dataIndex: "bootfile",
                    id: "bootfile",
					renderer: this.bootFileRenderer
				}]
			})
	};
	Ext.apply(initialConfig, config);
	OMV.Module.Services.DHCPDReservationsGridPanel.superclass.constructor.call(
			this, initialConfig);
};

Ext.extend(OMV.Module.Services.DHCPDReservationsGridPanel, OMV.grid.TBarGridPanel, {

	initComponent : function() {
		this.store = new OMV.data.Store({
			autoLoad: false,
			remoteSort: false,
			proxy: new OMV.data.DataProxy("dhcpd", "getReservations"),
			reader: new Ext.data.JsonReader({
				idProperty: "uuid",
				totalProperty: "total",
				root: "data",
				fields: [
			         { name: "uuid" },
			         { name: "name" },
			         { name: "ip" },
			         { name: "bootfile" },
			         { name: "bootconfig" },
			         { name: "mac" }
		         ]
			})
		});
		OMV.Module.Services.DHCPDReservationsGridPanel.superclass.initComponent.
		apply(this, arguments);
	},

    bootFileRenderer : function(val, cell, record) {
		switch(record.data.bootconfig) {

			case '..none': return "None";
			case '..specify': return record.data.bootfile;
			default:
				return "Server Default";
		}
    },

	initToolbar : function() {
		var tbar = OMV.Module.Services.DHCPDReservationsGridPanel.superclass.initToolbar.apply(this);

		return tbar;
	},

	listeners : {

		show: function() {
			this.doLoad();
		}

	},
	cbAddBtnHdl : function() {
		var wnd = new OMV.Module.Services.DHCPDReservationPropertyDialog({
			uuid: OMV.UUID_UNDEFINED,
			listeners: {
				submit: function() {
					this.doReload();
				},
				scope: this
			}
		});
		wnd.show();
	},

	cbEditBtnHdl : function() {
		var selModel = this.getSelectionModel();
		var record = selModel.getSelected();
		var wnd = new OMV.Module.Services.DHCPDReservationPropertyDialog({
			uuid: record.get("uuid"),
			listeners: {
				submit: function() {
					this.doReload();
				},
				scope: this
			}
		});
		wnd.show();
	},

	doDeletion : function(record) {
		OMV.Ajax.request(this.cbDeletionHdl, this, "dhcpd", "removeReservation",
				[ record.get("uuid") ]);
	}


});

OMV.Module.Services.DHCPDLeasesGridPanel = function(config) {

	var initialConfig = {
			disabled: true,
			hideAdd: true,
			hideEdit: true,
			hideDelete: true,
			hideRefresh: false,
			hidePagingToolbar: false,
			colModel: new Ext.grid.ColumnModel({
				columns: [{
					header: "Computer Name",
					sortable: true,
					dataIndex: "name",
					id: "name"
				},{
					header: "IP Address",
					sortable: true,
					dataIndex: "ip",
					id: "ip"
				},{
					header: "MAC Address",
					sortable: true,
					dataIndex: "mac",
					id: "mac"
				},{
					header: "Expires",
					sortable: true,
					dataIndex: "exp",
					id: "exp"
				}]
			})
	};
	Ext.apply(initialConfig, config);
	OMV.Module.Services.DHCPDLeasesGridPanel.superclass.constructor.call(
			this, initialConfig);
};

Ext.extend(OMV.Module.Services.DHCPDLeasesGridPanel, OMV.grid.TBarGridPanel, {

	initComponent : function() {
		this.store = new OMV.data.Store({
			autoLoad: false,
			remoteSort: false,
			proxy: new OMV.data.DataProxy("dhcpd", "getLeaseList"),
			reader: new Ext.data.JsonReader({
				idProperty: "ip",
				totalProperty: "total",
				root: "data",
				fields: [
				         { name: "name" },
				         { name: "ip" },
				         { name: "exp" },
				         { name: "mac" }
				         ]
			})
		});
		OMV.Module.Services.DHCPDLeasesGridPanel.superclass.initComponent.
		apply(this, arguments);
	},

	listeners : {
		show: function() {
			this.doLoad();
		}
	},

	initToolbar : function() {
		var tbar = OMV.Module.Services.DHCPDLeasesGridPanel.superclass.initToolbar.apply(this);
		return tbar;
	}


});

OMV.NavigationPanelMgr.registerPanel("services", "dhcpd", {
	cls: OMV.Module.Services.DHCPDSettingsPanel,
	position : 10,
	title : "Settings"
});

OMV.NavigationPanelMgr.registerPanel("services", "dhcpd", {
	cls: OMV.Module.Services.DHCPDReservationsGridPanel,
	position : 20,
	title : "Reservations"
});

OMV.NavigationPanelMgr.registerPanel("services", "dhcpd", {
	cls: OMV.Module.Services.DHCPDLeasesGridPanel,
	position : 30,
	title : "Leases"
});


OMV.Module.Services.DHCPDReservationPropertyDialog = function(config) {
	var initialConfig = {
			rpcService: "dhcpd",
			rpcGetMethod: "getReservation",
			rpcSetMethod: "setReservation",
			title: ((config.uuid == OMV.UUID_UNDEFINED) ? "Add" : "Edit") +
			" Reservation",
			autoHeight: true
	};
	Ext.apply(initialConfig, config);
	OMV.Module.Services.DHCPDReservationPropertyDialog.superclass.constructor.call(
			this, initialConfig);
};

Ext.extend(OMV.Module.Services.DHCPDReservationPropertyDialog, OMV.CfgObjectDialog, {
	initComponent : function() {
		OMV.Module.Services.DHCPDReservationPropertyDialog.superclass.initComponent.
		apply(this, arguments);
		this.on("load", this._updateFormFields, this);
	},

	getFormConfig : function() {
		return {
			autoHeight: true
		};
	},

	getFormItems : function() {
		return [{
			xtype: "textfield",
			name: "name",
			vtype: "hostname",
			itemId: "name",
			fieldLabel: "Computer Name",
			allowBlank: false
		},{
			xtype: "textfield",
			name: "ip",
			itemId: 'ip',
			vtype: "IPv4",
			fieldLabel: "IP Address",
			allowBlank: false
		},{
			xtype: "textfield",
			name: "mac",
			itemId: "mac",
			id: this.getId() + '-mac',
			fieldLabel: "MAC Address",
			allowBlank: false
		},{
			xtype: "combo",
			name: "exlease",
			hiddenName: "exlease",
			fieldLabel: "",
			emptyText: "Select existing lease ...",
			allowBlank: true,
			allowNone: true,
			width: 300,
			editable: false,
			triggerAction: "all",
			displayField: "disp",
			valueField: "mac",
			listeners: {
				select: function(a,b,c) {
					this.ownerCt.getComponent('ip').setValue(b.data.ip);
					this.ownerCt.getComponent('mac').setValue(b.data.mac);
					this.ownerCt.getComponent('name').setValue(b.data.name);
				}
			},
			store: new OMV.data.Store({
				remoteSort: false,
				proxy: new OMV.data.DataProxy("DHCPD", "getLeases"),
				reader: new Ext.data.JsonReader({
					idProperty: "mac",
					fields: [
					         { name: "ip" },
					         { name: "mac" },
					         { name: "name" },
					         { name: "disp" }
					         ]
				})
			})
		},{
			xtype: "label",
			text: "TFTP Boot",
			fieldLabel : " "
        },{
            xtype: "combo",
            name: "bootconfig",
            fieldLabel: "Policy",
            allowBlank: false,
            displayField: "text",
            valueField: "value",
            value : "..default",
            triggerAction: "all",
            mode : "local",
            listeners: {
                select: function(a,b,c) {
                    this.ownerCt.getComponent('bootfile').setDisabled(b.data.value != '..specify');
                    this.ownerCt.getComponent('bootfile').allowBlank = (b.data.value != '..specify');
                    this.ownerCt.getComponent('ip').allowBlank = (b.data.value != '..default');
                }
            },
            store : new Ext.data.SimpleStore({
                fields: [ "value","text" ],
                data: [
                   ["..default","Server Default"],
                   ["..none","None"],
                   ["..specify","Specify boot file"]
               ]
            })
        },{
            xtype: "textfield",
            name: "bootfile",
            fieldLabel: "TFTP Boot File",
			itemId: "bootfile",
            allowBlank: true,
            disabled: true,
            width : 300,
            value : "",
            plugins: [ OMV.form.plugins.FieldInfo ],
            infoText: "If set, this file must exist on the TFTP share."
		}];
	},
	
	/**
	 * Private function to update the states of various form fields.
	 */
	_updateFormFields : function() {
		if ((this.uuid !== OMV.UUID_UNDEFINED)) {
			var field1 = this.findFormField("name");
			var field2 = this.findFormField("mac");
			var field3 = this.findFormField("exlease");
			field1.setReadOnly(true);
			field2.setReadOnly(true);
			field3.hide();
		}

		var bootconf = this.findFormField('bootconfig').value;
		var field1 = this.findFormField('bootfile');
		var field2 = this.findFormField('ip');
        field1.setDisabled(bootconf != '..specify');
        field1.allowBlank = (bootconf != '..specify');
        field2.allowBlank = (!field1.allowBlank);
	}
});

